package v1

import (
	"blog/model"
	"blog/model/response"
	"blog/utils/validate"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// AddUser 添加用户
func AddUser(c *gin.Context) {
	var user model.User
	_ = c.ShouldBindJSON(&user)
	msg, code := validate.Validate(&user)
	if code != response.SUCCESS {
		c.JSON(
			http.StatusOK, gin.H{
				"status":  code,
				"message": msg,
			},
		)
		return
	}
	code = model.CheckUsername(user.Username)
	if code == response.SUCCESS {
		model.CreateUser(&user)
	}
	c.JSON(
		http.StatusOK, gin.H{
			"status":  code,
			"message": response.GetMessage(code),
		},
	)

}

// GetUserInfo 查询单个用户
func GetUserInfo(c *gin.Context) {

}

// GetUsers 查询用户列表
func GetUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	if pageNum == 0 {
		pageNum = -1
	}
	code := response.SUCCESS
	users := model.GetUsers(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    users,
		"message": response.GetMessage(code),
	})
}

// EditUser 编辑用户
func EditUser(c *gin.Context) {
	var user model.User
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&user)
	code := model.CheckUsername(user.Username)
	if code == response.SUCCESS {
		model.EditUser(id, &user)
	}
	if code == response.ERROR_USERNAME_USED {
		c.Abort()

	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": response.GetMessage(code),
	})
}

// ChangeUserPassword 修改密码
func ChangeUserPassword(c *gin.Context) {

}

// DeleteUser 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": response.GetMessage(code),
	})
}
